package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;
    @Autowired
    private UserAccountMapper userAccountMapper;

    @Override
    public JSONObject submitRecharge(RechargeInfoVo rechargeInfoVo) {

        RechargeInfo rechargeInfo = new RechargeInfo();
        rechargeInfo.setUserId(AuthContextHolder.getUserId());
        String orderNo = IdUtil.getSnowflakeNextIdStr();
        rechargeInfo.setOrderNo(orderNo);
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
        rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
        rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
        rechargeInfoMapper.insert(rechargeInfo);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNo" , orderNo);
        return jsonObject;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateRechargeByOrderNo(String orderNo, String orderStatus) {
        //1、更新交易记录的状态
        RechargeInfo rechargeInfo = this.getOne(Wrappers.lambdaQuery(RechargeInfo.class)
                .eq(RechargeInfo::getOrderNo, orderNo)
                .eq(RechargeInfo::getRechargeStatus, SystemConstant.ORDER_STATUS_UNPAID));
        if(rechargeInfo==null){
            return false;
        }
        rechargeInfo.setRechargeStatus(orderStatus);
        this.updateById(rechargeInfo);
        //2、更新账户余额
        userAccountMapper
                .updateAmount(rechargeInfo.getUserId() , rechargeInfo.getRechargeAmount());

        return true;
    }
}
